package com.azt.front.action.integral;

import com.alibaba.fastjson.JSONObject;
import com.azt.api.dto.GiftInfoData;
import com.azt.api.pojo.*;
import com.azt.api.service.*;
import com.azt.front.action.BaseAction;
import com.azt.front.permission.RequireUser;
import com.azt.front.utils.ContextUtil;
import com.azt.model.AjaxJson;
import com.azt.model.page.Pagination;
import com.azt.utils.FormatUtil;
import com.azt.utils.RequestUtils;
import com.xiaoleilu.hutool.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/integral")
public class IntegralShopAction  extends BaseAction {
	
	@Autowired
	private IntegralService integralService;
	@Autowired
	private PrizeRecordService prizeRecordService;
	@Autowired
	private PrizeSetService prizeSetService;
	@Autowired
	private GiftService giftService;
	@Autowired
	private UserService userService;
	@Autowired
	private MsgConfigService msgConfigService;
	//积分商城列表页
	@RequestMapping("/integralShop")
	public String integralShop(Integer pageNo,HttpServletRequest request , HttpServletResponse response , Model model){
		User user = ContextUtil.getUser();
		if(user!=null){
			//获取用户的一些数据
			Date date=new Date();
			//今日获得积分
			Integer sinceIntegral = integralService.getSinceIntegralRecordByUserId(user.getId(),1,1,new SimpleDateFormat("yyyy-MM-dd").format(date));
			//用户当前积分信息
			UserAccount userAccount = userService.getUserAccountByUserId(user.getId());
			//获取规则数据
			model.addAttribute("sinceIntegral", sinceIntegral);//今日获得积分
			model.addAttribute("userAccount", userAccount);//积分账户
			int signCount=integralService.selectSignRecord(user.getId(),"sign_in");
			model.addAttribute("signCount", signCount);
		}
		List<IntegralRecord> integralInstruct = integralService.getIntegralRecordInstruct();
		model.addAttribute("integralInstruct", integralInstruct);//积分规则说明
		//获奖列表
		List<PrizeRecord> allPrizeRecord = prizeRecordService.selectRecords(0,20);
		//奖品列表
		List<PrizeSet> allPrizeSet = prizeSetService.selectPrizeSets(0,20);
		//判断是否签到
		model.addAttribute("isload", 0);
		model.addAttribute("user", user);
		model.addAttribute("allPrizeRecord", allPrizeRecord);
		model.addAttribute("allPrizeSet", allPrizeSet);
		return "integral/integralShop";
	}
	
	//切换不刷新页面
	@RequestMapping("/ajaxIntegralShop")
	public String ajaxIntegralShop(Integer pageNo,HttpServletRequest request , HttpServletResponse response , Model model){
		User user = ContextUtil.getUser();
		Map<String, String> searchMap=RequestUtils.getSearchMap(request);
		if(user!=null){
			searchMap.put("userId", user.getId().toString());
		}
		//礼品列表
		Pagination page=giftService.searchGift(pageNo==null?1:pageNo,15, searchMap);//15个一页
		model.addAttribute("isload", 1);
		model.addAttribute("pagination", page);
		return "integral/integralTab";
	}
	
	
	//积分抽奖方法
	@RequireUser
	@ResponseBody
	@RequestMapping("/draw")
	public JSONObject drawFuction(){
		JSONObject json =new JSONObject();
		//登陆
		User user = ContextUtil.getUser();
		if(user!=null){
			Map<String, Object> drawIngral = integralService.drawIngral(user);
			UserAccount userAccount = userService.getUserAccountByUserId(user.getId());
			drawIngral.put("usIntegral", userAccount.getUsIntegral());
			json.put("drawIngral", drawIngral);
		}else{
			//未登陆
			json.put("result", 4);
		}
		return json;
	}
	
	//验证用户是否登录
	@RequireUser
	@ResponseBody
	@RequestMapping("/isSign")
	public AjaxJson isSign(){
		User user = ContextUtil.getUser();
		int signCount=integralService.selectSignRecord(user.getId(),"sign_in");
		if(signCount==0){
				integralService.addUserRecord(user.getId(), "sign_in", null, null, null);
				return AjaxJson.success();
			}
		else
			return AjaxJson.error();	
	}
	//验证用户是否登录
	@RequireUser
	@ResponseBody
	@RequestMapping("/islog")
	public AjaxJson isLog(){
		return AjaxJson.success();
	}
		
	//用户中心我的积分
	@RequireUser
	@RequestMapping("/myIntegral")
	public String myIntegral(Integer pageNo,HttpServletRequest request , HttpServletResponse response , Model model){
		User user = ContextUtil.getUser();
		Map<String, String> searchMap=RequestUtils.getSearchMap(request);
		searchMap.put("so_userId", user.getId().toString());
		//用户当前积分信息
		UserAccount userAccount = userService.getUserAccountByUserId(user.getId());
		//我的积分列表
		Pagination page= integralService.selectIntegralList(pageNo == null ? 1 : pageNo, 12,  searchMap);
		//上一年
		Integer lastYear = FormatUtil.getLastYear();
		//当年最后一天
		Date currYearLastDay = FormatUtil.getCurrYearLast();
		//用户即将失效的积分
		Integer lostIntegralNum = 0;
		Integer overIntegral= integralService.getOverIntegralRecordByUserId(user.getId(), 1, lastYear);
		Integer disIntegral=userAccount == null ? 0 : userAccount.getDisIntegral();
		if(disIntegral<overIntegral){
			lostIntegralNum = overIntegral-disIntegral;
		}
		model.addAttribute("lostIntegralNum", lostIntegralNum);
		model.addAttribute("currYearLastDay", currYearLastDay);
		model.addAttribute("userAccount", userAccount);
		model.addAttribute("pagination", page);
		return "integral/myIntegral";
	}
	
	//积分规则详情页面
	@RequestMapping("/integralRuleDetail")
	public String integralRuleDetail(Model model){
		List<IntegralRecord> integralInstruct = integralService.getIntegralRecordInstruct();
		model.addAttribute("integralInstruct", integralInstruct);//积分规则说明
		return "integral/integralRule";
	}
	
	// 保存中奖地址
	@RequireUser
	@ResponseBody
	@RequestMapping("/saveIntegralAddress")
	public AjaxJson drawAddress(PrizeRecord pr) {
		try {
			User user = ContextUtil.getUser();
			if (pr.getId() != null) {
				PrizeRecord PrizeRecord = prizeRecordService.selectPrizeRecordById(pr.getId());
				if (PrizeRecord != null && user.getId().equals(PrizeRecord.getUserId())) {
					prizeRecordService.SaveOrUpdateRecord(pr);
					Map<String, String> params = new HashMap<String, String>();
					params.put("user", StrUtil.isNotBlank(user.getMobile()) ? user.getMobile() : user.getEmail());
					PrizeSet prize = prizeSetService.getPrizeSetById(PrizeRecord.getPrizeId());
					params.put("gift", prize.getGiftName());
					msgConfigService.sendMessage("AUDIT_INTEGRAL" , params , null , new ArrayList());//通知运营人员
					return AjaxJson.success();
				} else {
					return AjaxJson.error();
				}
			} else {
				return AjaxJson.error();
			}
		} catch (Exception e) {
			LOGGER.error("save integral address error", e);
			return AjaxJson.error();
		}

	}
	
	    //放弃奖品
		@ResponseBody
		@RequestMapping("/dropPrizeRecord")
		public AjaxJson dropPrizeRecord(PrizeRecord pr){
			if(pr!=null){
				prizeRecordService.delRecordById(pr);
				return AjaxJson.success();
				
			}else{
				return AjaxJson.error();
			}
			
		}
		
		//礼品详情页
		@RequestMapping("/giftDetail/{id}")
		public String giftDetail(ModelMap model,HttpServletRequest request , HttpServletResponse response , @PathVariable("id") Integer id){
			User user = ContextUtil.getUser();
			if(user!=null){
				//用户当前积分信息
				UserAccount userAccount = userService.getUserAccountByUserId(user.getId());
				//获取规则数据
				model.addAttribute("userAccount", userAccount);//积分账户
			}
			//奖品列表
			List<GiftInfoData> hotGifts = giftService.selectHotGifts(0,6,0);
			GiftInfoData giftInfo=giftService.selectGiftInfoDetail(id);
			model.addAttribute("gi", giftInfo);
			model.addAttribute("hotGifts", hotGifts);
			model.addAttribute("user", user);
			return "integral/giftDetail";
		}
		
	// 兑换礼品
	@RequireUser
	@ResponseBody
	@RequestMapping("/exchangeIntegral")
	public AjaxJson exchangeIntegral(GiftExchange ge) {
		try {
			User user = ContextUtil.getUser();
			String msg = integralService.exchageGift(user, ge);
			return AjaxJson.success(msg);
		} catch (Exception e) {
			return AjaxJson.error("兑换失败");
		}
	}

}
